﻿using System.IO.IsolatedStorage;
using System.Runtime.Serialization;
using System.Collections.ObjectModel;
using System.IO;

namespace T163.Open.Api.WP7.Sample.Utility
{
    public class IsoStoreHelper
    {
        public static void Add(string key, object value)
        {
            IsolatedStorageSettings settings = IsolatedStorageSettings.ApplicationSettings;
            settings[key] = value;
            settings.Save();
        }

        public static T Get<T>(string key)
        {
            IsolatedStorageSettings settings = IsolatedStorageSettings.ApplicationSettings;
            T obj;
            if (settings.TryGetValue<T>(key, out obj))
                return obj;
            else
                return default(T);
        }

        public static bool Delete(string key)
        {
            IsolatedStorageSettings settings = IsolatedStorageSettings.ApplicationSettings;
            bool result = settings.Remove(key);
            settings.Save();

            return result;
        }

        public static bool IsExist(string key)
        {
            IsolatedStorageSettings settings = IsolatedStorageSettings.ApplicationSettings;
            return settings.Contains(key);
        }

        public static void SaveList<T>(string folderName, string dataName, ObservableCollection<T> dataList) where T : class
        {
            IsolatedStorageFile isoStore = IsolatedStorageFile.GetUserStoreForApplication();

            if (!isoStore.DirectoryExists(folderName))
            {
                isoStore.CreateDirectory(folderName);
            }

            string fileStreamName = string.Format("{0}\\{1}.dat", folderName, dataName);

            using (IsolatedStorageFileStream stream = new IsolatedStorageFileStream(fileStreamName, FileMode.Create, isoStore))
            {
                DataContractSerializer dcs = new DataContractSerializer(typeof(ObservableCollection<T>));
                dcs.WriteObject(stream, dataList);
            }
        }

        public static ObservableCollection<T> LoadList<T>(string folderName, string dataName) where T : class
        {
            IsolatedStorageFile isoStore = IsolatedStorageFile.GetUserStoreForApplication();

            ObservableCollection<T> retval = new ObservableCollection<T>();

            string fileStreamName = string.Format("{0}\\{1}.dat", folderName, dataName);

            using (IsolatedStorageFileStream stream = new IsolatedStorageFileStream(fileStreamName, FileMode.OpenOrCreate, isoStore))
            {
                if (stream.Length > 0)
                {
                    DataContractSerializer dcs = new DataContractSerializer(typeof(ObservableCollection<T>));
                    retval = dcs.ReadObject(stream) as ObservableCollection<T>;
                }
            }

            return retval;
        }
    }
}
